﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using The_Last_Knights.GUI;

namespace The_Last_Knights.Helper.Xml
{
    public class GroupboxReader: ReaderEntity
    {        
        public override object Read(XElement element, string ID, int level)
        {
            string blankDir = null;
            try
            {
                 blankDir = element.Attribute(XName.Get(@"Background")).Value;    
            }
            catch(Exception){}
            
            Dictionary<string, object> dictionary = new Dictionary<string, object>();  
            Vector2[] vector2s = new Vector2[2];
            int index = 0;
            var defs = element.Descendants(XName.Get(@"Element"));
            foreach (var xElement in defs)
            {
                string name = xElement.Attribute(XName.Get(@"ID")).Value;
                string id = XmlReader.TranslateID(name);
                string type = xElement.Attribute(XName.Get(@"Type")).Value;
                int lev = int.Parse(xElement.Attribute(XName.Get(@"Level")).Value);
                if (lev == level + 1)
                    switch (type)
                    {
                        case "Vector2":
                            vector2s[index] = (Vector2) Factory.Read(xElement, name, type, lev);
                            index++;
                            break;
                        default:
                            dictionary.Add(id, Factory.Read(xElement, id, type, lev));
                            break;
                    }                
            }
            Texture2D background = null;
            if (blankDir != null && blankDir != "")
                background = Game.Content.Load<Texture2D>(GameAssertPath.GUI_TEXTURE_PATH + blankDir);
            Groupbox groupbox = new Groupbox(Game, ID, vector2s[0], vector2s[1], 
                background);
            foreach (var o in dictionary)
            {
                groupbox.AddElement(o.Key, (Element2D) o.Value);
                (o.Value as GameEntity).Parent = groupbox;
            }
            GameEntityDictionary.Add(dictionary);
            return groupbox;
        }
    }
}
